// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/2/23 02:24
// 文件名称 ：   handlers.go
// 工程名称 ：   videostream
// 开发工具 ：   GoLand
//

package main

import (
	"github.com/julienschmidt/httprouter"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)

func streamHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	//vid := ps.ByName("vid")
	//vl := VIDEO_DIR + vid
	//video, err := os.Open(vl)
	//if err != nil {
	//	sendErrorResponse(w, http.StatusInternalServerError, "Internal server error!")
	//	return
	//}
	//defer video.Close()
	//w.Header().Set("Content-Type", "video/mp4")
	//http.ServeContent(w, r, "", time.Now(), video)
	log.Println("Entered the streamHandler")
	targetUrl := "http://avenssi-videos2.oss-cn-qingdao.aliyuncs.com/videos/" + ps.ByName("vid")
	http.Redirect(w, r, targetUrl, 301)
}

func uploadHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
	if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
		sendErrorResponse(w, http.StatusBadRequest, "File is too big!")
		return
	}
	file, _, err := r.FormFile("file")
	if err != nil {
		sendErrorResponse(w, http.StatusInternalServerError, "Internal server error!")
		return
	}
	data, err := ioutil.ReadAll(file)
	if err != nil {
		sendErrorResponse(w, http.StatusInternalServerError, "Internal server error!")
		return
	}
	fn := ps.ByName("vid")
	err = ioutil.WriteFile(VIDEO_DIR+fn, data, 0666)
	if err != nil {
		sendErrorResponse(w, http.StatusInternalServerError, "Internal server error!")
		return
	}
	ossfn := "videos/" + fn
	path := "./videos/" + fn
	bn := "avenssi-videos2"
	ret := UploadToOss(ossfn, path, bn)
	if !ret {
		sendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	os.Remove(path)

	w.WriteHeader(http.StatusCreated)
	io.WriteString(w, "Uploaded successfully")
}
